package br.ucb.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import br.ucb.bean.Disciplina;
import br.ucb.bean.PlanoDeEnsino;
import br.ucb.dao.PlanoDeEnsinoDAO;
import br.ucb.util.SimpleEntityManager;

public class PlanoDeEnsinoController extends GenericController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private PlanoDeEnsinoDAO planoDAO;

	public PlanoDeEnsinoDAO getPlanoDAO() {
		return planoDAO;
	}

	public void setPlanoDAO(PlanoDeEnsinoDAO planoDAO) {
		this.planoDAO = planoDAO;
	}
	
	public void readyManagerAndDao() {
		setManager(new SimpleEntityManager("sacop"));
		this.planoDAO = new PlanoDeEnsinoDAO(getManager().getEntityManager());
		getManager().beginTransaction();
	}
	
	public List<PlanoDeEnsino> findPlanos() {
		List<PlanoDeEnsino> planos;
		
		if(getProfessor() == null){
			readyManagerAndDao();
			planos = this.planoDAO.listar();
			getManager().close();
		}else{
			List<Disciplina> disciplinas = new DisciplinaController().findDisciplinas();
			readyManagerAndDao();
			planos = findRelatedPlanos(disciplinas);
			getManager().close();
		}
		
		return planos;
	}

	private List<PlanoDeEnsino> findRelatedPlanos(List<Disciplina> disciplinas) {
		List<PlanoDeEnsino> planos = new ArrayList<PlanoDeEnsino>();
		for (Disciplina disciplina : disciplinas) {
			planos.addAll(this.planoDAO.buscarRelacionado("disciplina.codigo", disciplina.getCodigo()));
		}
		return planos;
	}
	
	public PlanoDeEnsino findPlanoByDisciplinaId(int id){
		PlanoDeEnsino plano;
		readyManagerAndDao();
		plano = getPlanoDAO().buscar("disciplina.codigo", id);
		getManager().close();
		return plano;
	}
	
	public PlanoDeEnsino findById(int id){
		PlanoDeEnsino plano;
		readyManagerAndDao();
		plano = getPlanoDAO().getById(id);
		getManager().close();
		return plano;
	}

}
